package com.etocrm.saas.lib.base.server.exception;

import com.aliyun.oss.OSSException;
import com.etocrm.saas.lib.base.common.exception.BaseException;
import com.etocrm.saas.lib.base.common.exception.CustomException;
import com.etocrm.saas.lib.base.common.exception.ErrorException;
import com.etocrm.saas.lib.base.common.exception.WarnException;
import com.etocrm.saas.lib.base.common.result.Result;
import com.etocrm.saas.lib.base.common.result.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 一个默认的全局异常处理
 * Created by Xs on 2022/11/16.
 */
@RestControllerAdvice
@Slf4j
public class DefaultGlobalExceptionHandler {

    private static final String LOG_TEMPLATE = "{} Exception: code={}, message={}, exception={}";

    private static final String LOG_TEMPLATE_FORMAT = "%s Exception: code=%s, message=%s, exception=%s";

    /**
     * 自定义异常处理
     */
    @ExceptionHandler(value = CustomException.class)
    public Result<Void> customExceptionHandler(CustomException e) {
        Result<Void> result = Result.fail(e.getMessage());
        logWarn(result, e);
        return result;
    }

    /**
     * 默认自定义异常处理
     */
    @ExceptionHandler(value = BaseException.class)
    public Result<Void> exceptionHandler(BaseException e) {
        Result<Void> result = Result.fail(e.getResultCodeEnum());
        if (e instanceof WarnException) {
            logWarn(result, e);
        } else if (e instanceof ErrorException) {
            logError(result, e);
        } else {
            logInfo(result, e);
        }
        return result;
    }


    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Result defaultExceptionHandler(HttpMessageNotReadableException httpMessageNotReadableException) {
        Result result = Result.fail(ResultCodeEnum.PARAM_VALID_ERROR);
        result.setMessage(result.getMessage() + httpMessageNotReadableException.getMessage());
        logWarn(result, httpMessageNotReadableException);
        return result;
    }


    /**
     * 参数校验异常(RequestBody json参数)
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {


        BindingResult bindingResult = e.getBindingResult();

        String collect = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(","));

        Result result = Result.fail(collect);
        logWarn(result, e);
        return result;
    }


    /**
     * 参数校验异常(RequestParam 参数)
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result bindExceptionHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();

        String collect = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(","));

        Result result = Result.fail(collect);
        logWarn(result, e);
        return result;
    }

    /**
     * aliyun oss异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({OSSException.class})
    public Result oSSExceptionHandler(OSSException e) {
        Result result = Result.fail(e.getErrorMessage());
        logWarn(result, e);
        return result;
    }

    @ExceptionHandler({Exception.class})
    public Result defaultExceptionHandler(Exception e) {
        if (e.getMessage().contains("不允许访问")) {
            Result result = Result.fail(ResultCodeEnum.USER_NO_PERMISSION_WARN);
            logError(result, e);
            return result;
        }
        Result result = Result.fail(ResultCodeEnum.SYSTEM_ERROR);
        logError(result, e);
        return result;
    }

    protected void logError(Result result, Exception e) {
        log.error(LOG_TEMPLATE, e.getClass().getSimpleName(), result.getResultCode(), result.getMessage(), e, e);
    }

    protected void logWarn(Result result, Exception e) {
        log.warn(LOG_TEMPLATE, e.getClass().getSimpleName(), result.getResultCode(), result.getMessage(), e);
    }

    protected void logInfo(Result result, Exception e) {
        log.info(LOG_TEMPLATE, e.getClass().getSimpleName(), result.getResultCode(), result.getMessage(), e);
    }
}
